package init

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"user-srv/basic/config"
	"user-srv/handler/models"
)

func InitMysql() {
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.AppConf.Mysql.User,
		config.AppConf.Mysql.Password,
		config.AppConf.Mysql.Host,
		config.AppConf.Mysql.Port,
		config.AppConf.Mysql.Database,
	)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("Mysql连接成功")
	}
	err = config.DB.AutoMigrate(&models.User{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("数据迁移成功")
	}
}
